package com.lst.tools.redis.config;

import com.lst.tools.redis.constant.RedisConstants;
import com.lst.tools.redis.properties.RedissonProperties;
import com.lst.tools.redis.properties.RedissonSentinelProperties;
import com.lst.tools.redis.properties.RedissonSingleProperties;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SubscriptionMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Redisson缓存连接配置
 *
 * @author: Frank
 * @date: 2019/09/24 13:51
 * @version: V1.0
 */
@Configuration
public class RedissonConfig extends CachingConfigurerSupport {

    @Autowired
    private RedissonProperties redissonProperties;
    @Autowired
    private RedissonSentinelProperties redissonSentinelProperties;
    @Autowired
    private RedissonSingleProperties redissonSingleProperties;

    /**
     * redissonClient配置
     *
     * @return
     */
    @Bean(destroyMethod = "shutdown")
    public RedissonClient redissonClient() {
        String mode = redissonProperties.getMode();
        if (RedisConstants.MODE_SINGLE.equalsIgnoreCase(mode)) {
            Config config = new Config();
            config.useSingleServer()
                    .setAddress(redissonSingleProperties.getAddress())
                    .setPassword(redissonSingleProperties.getPassword())
                    .setDatabase(redissonSingleProperties.getDatabase())
                    .setTimeout(redissonSingleProperties.getTimeout())
                    .setRetryAttempts(redissonSingleProperties.getRetryAttempts())
                    .setRetryInterval(redissonSingleProperties.getRetryInterval());
            return Redisson.create(config);
        } else if (RedisConstants.MODE_SENTINEL.equalsIgnoreCase(mode)) {
            String[] nodes = redissonSentinelProperties.getNodes().split(RedisConstants.NODE_SPLIT);
            Config config = new Config();
            config.useSentinelServers()
                    .setMasterName(redissonSentinelProperties.getMasterName())
                    .setSubscriptionMode(SubscriptionMode.SLAVE)
                    .setPassword(redissonSentinelProperties.getPassword())
                    .setDatabase(redissonSentinelProperties.getDatabase())
                    .setTimeout(redissonSentinelProperties.getTimeout())
                    .setRetryAttempts(redissonSentinelProperties.getRetryAttempts())
                    .setRetryInterval(redissonSentinelProperties.getRetryInterval())
                    .addSentinelAddress(nodes);
            return Redisson.create(config);
        }
        return null;

    }

}
